{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Table A8 (Appendices)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loaded: jcr_mutiny_conflict_data.dta  |  Rows=1,599,624  Cols=94\n",
      "┌─ FINAL OLS LaTeX TABLE ─────────────────────────────────────────────────\n",
      "\\begin{table}\n",
      "\\caption{}\n",
      "\\label{}\n",
      "\\begin{center}\n",
      "\\begin{tabular}{lllll}\n",
      "\\hline\n",
      "                   & Mutiny    & Violent   & Large     & Duration   \\\\\n",
      "\\hline\n",
      "Military mutiny          & 0.002***  &           &           &            \\\\\n",
      "                   & (0.000)   &           &           &            \\\\\n",
      "Violent mutiny         &           & 0.003***  &           &            \\\\\n",
      "                   &           & (0.001)   &           &            \\\\\n",
      "Large mutiny         &           &           & 0.002***  &            \\\\\n",
      "                   &           &           & (0.001)   &            \\\\\n",
      "Mutiny duration &           &           &           & 0.001***   \\\\\n",
      "                   &           &           &           & (0.000)    \\\\\n",
      "Military spending per soldier (logged) & -0.000    & -0.000*   & -0.000*   & -0.000     \\\\\n",
      "                   & (0.000)   & (0.000)   & (0.000)   & (0.000)    \\\\\n",
      "Year since the last coup & 0.000***  & 0.000***  & 0.000***  & 0.000***   \\\\\n",
      "                   & (0.000)   & (0.000)   & (0.000)   & (0.000)    \\\\\n",
      "Civil conflict  & 0.002***  & 0.002***  & 0.002***  & 0.002***   \\\\\n",
      "                   & (0.000)   & (0.000)   & (0.000)   & (0.000)    \\\\\n",
      "Defense alliance    & -0.001*** & -0.001*** & -0.001*** & -0.001***  \\\\\n",
      "                   & (0.000)   & (0.000)   & (0.000)   & (0.000)    \\\\\n",
      "Capability ratio            & 0.001***  & 0.001***  & 0.001***  & 0.001***   \\\\\n",
      "                   & (0.000)   & (0.000)   & (0.000)   & (0.000)    \\\\\n",
      "Both democracy               & -0.000**  & -0.000**  & -0.000**  & -0.000**   \\\\\n",
      "                   & (0.000)   & (0.000)   & (0.000)   & (0.000)    \\\\\n",
      "Major power         & 0.006***  & 0.006***  & 0.006***  & 0.006***   \\\\\n",
      "                   & (0.001)   & (0.001)   & (0.001)   & (0.001)    \\\\\n",
      "Constant          & 0.020***  & 0.020***  & 0.020***  & 0.020***   \\\\\n",
      "                   & (0.003)   & (0.003)   & (0.003)   & (0.003)    \\\\\n",
      "R-squared          & 0.003     & 0.003     & 0.003     & 0.003      \\\\\n",
      "R-squared Adj.     & 0.003     & 0.003     & 0.003     & 0.003      \\\\\n",
      "N                  & 1337819   & 1337819   & 1337819   & 1337819    \\\\\n",
      "R²                 & 0.003     & 0.003     & 0.003     & 0.003      \\\\\n",
      "Year Fixed Effects & \\checkmark & \\checkmark & \\checkmark & \\checkmark \\\\\n",
      "Clustered SE (unit) & \\checkmark & \\checkmark & \\checkmark & \\checkmark \\\\\n",
      "\\hline\n",
      "\\end{tabular}\n",
      "\\end{center}\n",
      "\\end{table}\n",
      "\\bigskip\n",
      "Standard errors in parentheses. \\newline \n",
      "* p<.1, ** p<.05, ***p<.01\n",
      "└─────────────────────────────────────────────────────────────────────────\n",
      "Saved to: C:\\Users\\rmuhi\\OneDrive\\Desktop\\Mutiny_Conflict Paper_All\\Replication File\\fe_table1.tex\n"
     ]
    }
   ],
   "source": [
    "# --------------------------------------------------------\n",
    "# 0) Lightweight installer if packages are missing\n",
    "# --------------------------------------------------------\n",
    "try:\n",
    "    import pandas as _pd; import statsmodels as _sm; import matplotlib as _mpl\n",
    "except Exception:\n",
    "    import sys, subprocess\n",
    "    subprocess.check_call(\n",
    "        [sys.executable, \"-m\", \"pip\", \"install\", \"-U\",\n",
    "         \"pandas\", \"statsmodels\", \"matplotlib\"]\n",
    "    )\n",
    "\n",
    "from pathlib import Path\n",
    "import pandas as pd\n",
    "import statsmodels.formula.api as smf\n",
    "from statsmodels.iolib.summary2 import summary_col\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "\n",
    "# ----------------------------\n",
    "# 1) Load data\n",
    "# ----------------------------\n",
    "file_path = Path(\n",
    "    r\"C:\\Users\\rmuhi\\OneDrive\\Desktop\\Mutiny_Conflict Paper_All\\Replication File\\jcr_mutiny_conflict_data.dta\"\n",
    ")\n",
    "if not file_path.exists():\n",
    "    raise FileNotFoundError(f\"Could not find .dta file at: {file_path}\")\n",
    "\n",
    "data = pd.read_stata(file_path)\n",
    "print(f\"Loaded: {file_path.name}  |  Rows={len(data):,}  Cols={len(data.columns)}\")\n",
    "\n",
    "# ----------------------------\n",
    "# 2) Define model formulas\n",
    "#    (cold_war dropped; year FE via C(year))\n",
    "#    NOTE: mduration_t_cat3 is now USED AS CONTINUOUS (no C())\n",
    "# ----------------------------\n",
    "formula1 = (\n",
    "    \"dispute2 ~ mutiny_t + lmmilex_persol_t + years_since_coup  + \"\n",
    "    \"ucdp_civconf_t2 + defense_target + capprop + jdem + majorpower + C(year)\"\n",
    ")\n",
    "formula2 = (\n",
    "    \"dispute2 ~ violent_t + lmmilex_persol_t + years_since_coup + \"\n",
    "    \"ucdp_civconf_t2 + defense_target + capprop + jdem + majorpower + C(year)\"\n",
    ")\n",
    "formula3 = (\n",
    "    \"dispute2 ~ size_t_b + lmmilex_persol_t + years_since_coup + \"\n",
    "    \"ucdp_civconf_t2 + defense_target + capprop + jdem + majorpower + C(year)\"\n",
    ")\n",
    "# duration now continuous: mduration_t_cat3\n",
    "formula4 = (\n",
    "    \"dispute2 ~ mduration_t_cat3 + lmmilex_persol_t + years_since_coup + \"\n",
    "    \"ucdp_civconf_t2 + defense_target + capprop + jdem + majorpower + C(year)\"\n",
    ")\n",
    "\n",
    "# ----------------------------\n",
    "# 3) Drop missing values & estimate models\n",
    "# ----------------------------\n",
    "\n",
    "# Base list of variables used in all models\n",
    "base_vars = [\n",
    "    \"lmmilex_persol_t\",\n",
    "    \"years_since_coup\",\n",
    "    \"ucdp_civconf_t2\",\n",
    "    \"defense_target\",\n",
    "    \"capprop\",\n",
    "    \"jdem\",\n",
    "    \"majorpower\",\n",
    "    \"year\",   # needed for C(year)\n",
    "    \"id\"      # clustering unit\n",
    "]\n",
    "\n",
    "used_vars1 = [\"mutiny_t\"] + base_vars\n",
    "data1 = data.dropna(subset=used_vars1)\n",
    "model1 = smf.ols(formula1, data=data1).fit(\n",
    "    cov_type=\"cluster\",\n",
    "    cov_kwds={\"groups\": data1[\"id\"]}\n",
    ")\n",
    "\n",
    "used_vars2 = [\"violent_t\"] + base_vars\n",
    "data2 = data.dropna(subset=used_vars2)\n",
    "model2 = smf.ols(formula2, data=data2).fit(\n",
    "    cov_type=\"cluster\",\n",
    "    cov_kwds={\"groups\": data2[\"id\"]}\n",
    ")\n",
    "\n",
    "used_vars3 = [\"size_t_b\"] + base_vars\n",
    "data3 = data.dropna(subset=used_vars3)\n",
    "model3 = smf.ols(formula3, data=data3).fit(\n",
    "    cov_type=\"cluster\",\n",
    "    cov_kwds={\"groups\": data3[\"id\"]}\n",
    ")\n",
    "\n",
    "used_vars4 = [\"mduration_t_cat3\"] + base_vars\n",
    "data4 = data.dropna(subset=used_vars4)\n",
    "model4 = smf.ols(formula4, data=data4).fit(\n",
    "    cov_type=\"cluster\",\n",
    "    cov_kwds={\"groups\": data4[\"id\"]}\n",
    ")\n",
    "\n",
    "# ----------------------------\n",
    "# 4) Build LaTeX table\n",
    "# ----------------------------\n",
    "\n",
    "# Now we have ONE coefficient for mduration_t_cat3\n",
    "regressor_order = [\n",
    "    \"mutiny_t\",\n",
    "    \"violent_t\",\n",
    "    \"size_t_b\",\n",
    "    \"mduration_t_cat3\",\n",
    "    \"lmmilex_persol_t\",\n",
    "    \"years_since_coup\",\n",
    "    \"ucdp_civconf_t2\",\n",
    "    \"defense_target\",\n",
    "    \"capprop\",\n",
    "    \"jdem\",\n",
    "    \"majorpower\",\n",
    "    \"Intercept\"\n",
    "]\n",
    "\n",
    "info_dict = {\n",
    "    \"N\":  lambda x: f\"{int(x.nobs)}\",\n",
    "    \"R²\": lambda x: f\"{x.rsquared:.3f}\"\n",
    "}\n",
    "\n",
    "table = summary_col(\n",
    "    results=[model1, model2, model3, model4],\n",
    "    float_format=\"%0.3f\",\n",
    "    stars=True,\n",
    "    model_names=[\"Mutiny\", \"Violent\", \"Large\", \"Duration\"],\n",
    "    info_dict=info_dict,\n",
    "    drop_omitted=True,\n",
    "    regressor_order=regressor_order\n",
    ")\n",
    "\n",
    "# Convert to LaTeX lines\n",
    "latex_lines = table.as_latex().splitlines()\n",
    "\n",
    "# Insert Year FE & clustered SE rows just under R² row\n",
    "for i, line in enumerate(latex_lines):\n",
    "    if \"R²\" in line:\n",
    "        latex_lines.insert(\n",
    "            i + 1,\n",
    "            r\"Year Fixed Effects & \\checkmark & \\checkmark & \\checkmark & \\checkmark \\\\\"\n",
    "        )\n",
    "        latex_lines.insert(\n",
    "            i + 2,\n",
    "            r\"Clustered SE (unit) & \\checkmark & \\checkmark & \\checkmark & \\checkmark \\\\\"\n",
    "        )\n",
    "        break\n",
    "\n",
    "# Remove all explicit C(year) coefficient lines (keep only the FE checkmark row)\n",
    "filtered_lines = [\n",
    "    line for line in latex_lines\n",
    "    if \"C(year)\" not in line\n",
    "]\n",
    "\n",
    "# Variable label replacements (note escaped underscores)\n",
    "replacements = {\n",
    "    \"mutiny\\\\_t\": \"Military mutiny\",\n",
    "    \"violent\\\\_t\": \"Violent mutiny\",\n",
    "    \"size\\\\_t\\\\_b\": \"Large mutiny\",\n",
    "    \"mduration\\\\_t\\\\_cat3\": \"Mutiny duration\",\n",
    "    \"lmmilex\\\\_persol\\\\_t\": \"Military spending per soldier (logged)\",\n",
    "    \"years\\\\_since\\\\_coup\": \"Year since the last coup\",\n",
    "    \"ucdp\\\\_civconf\\\\_t2\": \"Civil conflict\",\n",
    "    \"defense\\\\_target\": \"Defense alliance\",\n",
    "    \"capprop\": \"Capability ratio\",\n",
    "    \"jdem\": \"Both democracy\",\n",
    "    \"majorpower\": \"Major power\",\n",
    "    \"Intercept\": \"Constant\",\n",
    "    \"const\": \"Constant\"\n",
    "}\n",
    "\n",
    "fixed_lines = []\n",
    "for line in filtered_lines:\n",
    "    for old, new in replacements.items():\n",
    "        line = line.replace(old, new)\n",
    "    fixed_lines.append(line)\n",
    "\n",
    "custom_latex = \"\\n\".join(fixed_lines)\n",
    "\n",
    "# ----------------------------\n",
    "# 5) Print and save LaTeX\n",
    "# ----------------------------\n",
    "print(\"┌─ FINAL OLS LaTeX TABLE ─────────────────────────────────────────────────\")\n",
    "for l in custom_latex.split(\"\\n\"):\n",
    "    print(l)\n",
    "print(\"└─────────────────────────────────────────────────────────────────────────\")\n",
    "\n",
    "# Save to .tex file\n",
    "output_path = r\"C:\\Users\\rmuhi\\OneDrive\\Desktop\\Mutiny_Conflict Paper_All\\Replication File\\table_A8.tex\"\n",
    "\n",
    "with open(output_path, \"w\", encoding=\"utf-8\") as f:\n",
    "    f.write(custom_latex)\n",
    "\n",
    "print(\"Saved to:\", output_path)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
